package fy.hr.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.soa.eis.adapter.framework.message.IMsgObject;
import com.soa.eis.adapter.framework.message.impl.GroupRecord;
import com.soa.eis.adapter.framework.message.impl.MsgObject;
import com.soa.eis.adapter.framework.requester.IServiceRequester;
import com.soa.eis.adapter.framework.requester.impl.BaseServiceRequester;

import fy.config.FyConfig;
import fy.hr.bean.AwayFormBean;
import fy.hr.constant.OA2HRConstant;
import fy.util.DBUtil;
import fy.util.MyUtil;
import fy.hr.dao.RequestNoTimerTask;
public class AwayFormDao3 {
	private AwayFormBean awayFormBean;
	private static Log log = LogFactory.getLog(AwayFormDao3.class);
	private final static String FIND_PERSONINFO_STR = "select t.pk_psndoc, t.pk_deptdoc,t.pk_corp from bd_psndoc t where  psnclscope='0' and ";
	private final static String FIND_PK_TBM_PSNDOC_STR = "select pk_tbm_psndoc, pk_psndoc from tbm_psndoc where to_date(enddate,'yyyy-mm-dd') > sysdate and (";
	private List<String> pk_psndocList;
	public boolean insertChuChaiInfo(String accountID) {
		boolean success = false;
		Connection conn = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			conn = DBUtil.connect(FyConfig.getEHR_DB_CONFIG());
			findPersonInfo(conn);
			if (pk_psndocList != null) {
				findPk_tbm_psndoc(conn);
				if (this.awayFormBean.getPersonList() != null) {
					conn.setAutoCommit(false);
					insertHR(accountID);
					conn.commit();
					success = true;
				} else {
					log.error(new StringBuilder().append("出差人员还未排班，出差数据写入HR失败。表单名称为：")
							.append(this.awayFormBean.getBillname()));
				}

			} else {
				log.error(new StringBuilder().append("工号填写不正确，导出失败。表单名称为：").append(this.awayFormBean.getBillname()));
			}

		} catch (Exception e) {
			DBUtil.rollback(conn);
			StringBuilder sb = new StringBuilder().append("表单《").append(awayFormBean.getBillname())
					.append("》数据写入HR数据库失败，单据编号为：").append(this.awayFormBean.getAwayid());
			log.error(sb, e);
			System.out.println(sb);
			e.printStackTrace();
		} finally {
			DBUtil.close(rs);
			DBUtil.close(pst);
			DBUtil.setAutoCommit(conn, true);
			DBUtil.close(conn);
		}
		awayFormBean = null;
		if (pk_psndocList != null)
			pk_psndocList.clear();
		pk_psndocList = null;
		return success;
	}


/*	  private void insertTbm_awayb(Connection conn,String accountID) throws
	  Exception { PreparedStatement pst = null; ResultSet rs = null; try { //
	  insert into tbm_awayb( aheadfee, ts, awayaddress, awaybeginday, //
	  awaybegintime, awayendday, awayendtime, awaynote, awaypsnorder, //
	 awaysumhour, pk_away_b, pk_away_h, pk_tbm_psndoc, psncode) values //
	  (?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
	  
	 pst = conn.prepareStatement(INSERT_TBM_AWAYB_SQL_STR);
	  
	  for (int i = 0, size = this.awayFormBean.getPersonList().size(); i <
	  size; i++) { pst.setString(1, this.awayFormBean.getAheadfee());
	  pst.setString(2, this.awayFormBean.getTs()); pst.setString(3,
	  this.awayFormBean.getAwayaddress()); pst.setString(4,
	 this.awayFormBean.getAwaybeginday()); pst.setString(5,
	  OA2HRConstant.getWorkTime( this.awayFormBean.getAwaybegintime(),
	  this.awayFormBean.getPk_corp(),accountID));
	 
	 
	  System.out.println("測試————————————" +OA2HRConstant.getWorkTime(
	  this.awayFormBean.getAwaybegintime(),
	  this.awayFormBean.getPk_corp(),accountID));
	  
	  pst.setString(6, this.awayFormBean.getAwayendday()); pst.setString(7,
	  OA2HRConstant.getWorkTime( this.awayFormBean.getAwayendtime(),
	  this.awayFormBean.getPk_corp(),accountID));
	  
	  System.out.println("測試————————————" +OA2HRConstant.getWorkTime(
	  this.awayFormBean.getAwayendtime(),
	  this.awayFormBean.getPk_corp(),accountID)); pst.setString( 8,
	  MyUtil.getLimitLengthString( this.awayFormBean.getAwaynote(), 500, "…"));
	  pst.setString(9, "0"); pst.setString(10,
	  this.awayFormBean.getAwaysumhour()); pst.setString(11,
	  MyUtil.createUUID()); pst.setString(12,
	  this.awayFormBean.getPk_away_h()); pst.setString(13,
	  this.awayFormBean.getPersonList().get(i) .getPk_tbm_psndoc());
	  pst.setString(14, this.awayFormBean.getPersonList().get(i)
	getPsncode());
	  
	  pst.addBatch(); }
	  
	  pst.executeBatch();
	 
	  } finally { DBUtil.close(rs); DBUtil.close(pst); } }
	  
	  private void insertTbm_awayh(Connection conn) throws Exception {
	  PreparedStatement pst = null; ResultSet rs = null; try { // insert into
	  tbm_awayh ( applier, applydate, // applydept,approvestatus, awayid,
	  awaytype, billname, isappbill, // ishrssbill,pk_away_h,pk_corp, ts )
	  values ( ?, ?, ?, ?, ?, ?, ?, // ?, ?, ?, ?, ?)
	  
	  pst = conn.prepareStatement(INSERT_TBM_AWAYH_SQL_STR);
	  awayFormBean.setPk_away_h(MyUtil.createUUID()); pst.setString(1,
	  this.awayFormBean.getApplier()); pst.setString(2,
	  this.awayFormBean.getApplydate()); pst.setString(3,
	 this.awayFormBean.getApplydept()); pst.setString(4, "200");
	 pst.setString(5, String.valueOf(this.awayFormBean.getSummaryId()));
	  pst.setString(6, this.awayFormBean.getAwaytype()); pst.setString(7,
	  MyUtil.getLimitLengthString( this.awayFormBean.getBillname(), 50, "…"));
	  pst.setString(8, "N"); pst.setString(9, "N"); pst.setString(10,
	  this.awayFormBean.getPk_away_h()); pst.setString(11,
	 this.awayFormBean.getPk_corp()); pst.setString(12,
	 this.awayFormBean.getTs());

	 pst.executeUpdate();

	 } finally { DBUtil.close(rs); DBUtil.close(pst); } }*/
	

	private void findPersonInfo(Connection conn) throws Exception {
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			// "select t.pk_psndoc, t.pk_deptdoc,t.pk_corp
			// from bd_psndoc t where psncode=? and psnclscope='0'";
			// pst = conn.prepareStatement(FIND_PERSONINFO_STR);

			StringBuilder sb = new StringBuilder().append(FIND_PERSONINFO_STR).append(" ( ");

			for (int i = 0, size = awayFormBean.getPersonCodeList().size(); i < size; i++) {

				if (i != 0) {
					sb.append(" or ");
				}
				sb.append(" psncode=? ");
			}

			sb.append(" ) ");

			st = conn.prepareStatement(sb.toString());
			sb = null;
			for (int i = 0, size = awayFormBean.getPersonCodeList().size(); i < size; i++) {
				st.setString(i + 1, awayFormBean.getPersonCodeList().get(i));
			}
			boolean first = true;
			rs = st.executeQuery();
			while (rs.next()) {

				if (pk_psndocList == null) {
					pk_psndocList = new ArrayList<String>();
				}

				pk_psndocList.add(rs.getString(1));

				if (first) {
					first = false;
					this.awayFormBean.setApplydept(rs.getString(2));
					this.awayFormBean.setPk_corp(rs.getString(3));
				}
			}
		} finally {
			DBUtil.close(rs);
			DBUtil.close(st);
		}
	}

	private void findPk_tbm_psndoc(Connection conn) throws Exception {
		PreparedStatement st = null;
		ResultSet rs = null;
		try {
			// "select pk_tbm_psndoc, pk_psndoc from tbm_psndoc where
			// pk_psndoc=?";
			StringBuilder sb = new StringBuilder();
			sb.append(FIND_PK_TBM_PSNDOC_STR);

			for (int i = 0, size = this.pk_psndocList.size(); i < size; i++) {

				if (i != 0) {
					sb.append(" or ");
				}
				sb.append(" pk_psndoc=? ");
			}
			sb.append(")");
			st = conn.prepareStatement(sb.toString());
			for (int i = 0, size = this.pk_psndocList.size(); i < size; i++) {
				st.setString(i + 1, pk_psndocList.get(i));
			}
			sb = null;
			rs = st.executeQuery();
			while (rs.next()) {
				awayFormBean.addPersonBean(rs.getString(1), rs.getString(2));
			}
		} finally {
			DBUtil.close(rs);
			DBUtil.close(st);
		}
	}

	public void setChuChaiBean(AwayFormBean chuChaiBean) {
		this.awayFormBean = chuChaiBean;
	}

	public static void main(String[] args) throws Exception {
		String temp = "取字符串的前toCount个字符";
		System.out.println(MyUtil.getLimitLengthString(temp, 36, "…"));
	}

	public void insertHR(String accountID) throws Exception {
	for (int i = 0, size = this.awayFormBean.getPersonList().size(); i < size; i++) {
			IServiceRequester Requester = BaseServiceRequester.getInstance();
			// 定义请求报文对象
			List<GroupRecord> grs1 = new ArrayList<GroupRecord>();
			IMsgObject reqMo = new MsgObject(IMsgObject.MOType.initSR);
			String SourceSysID = "06004"; // 请求方(发布方) 系统号
			String ServiceID = "06003000000005";// 响应方(发布方) 服务号
			// 获取系统时间
			Date date = new Date();
			SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
			String format = simpleDateFormat.format(date);
			// 对请求报文对象进行设置
			reqMo.setSerialNO(
					format.substring(0, 8) + SourceSysID + String.format("%06d", ++RequestNoTimerTask.requestNo));
			// reqMo.setSerialNO(format.substring(0, 8) + SourceSysID +
			// "000001");// 设置报文流水号,第三段表示今天发送的第几的一次报文
			reqMo.setServiceID(ServiceID); // 设置报文 提供方服务号
			reqMo.setServiceDateTime(format);
			reqMo.setSourceSysID(SourceSysID); // 设置报文 请求方系统号
			reqMo.setControlValue("", null);
			GroupRecord gr1 = new GroupRecord();
			awayFormBean.setPk_away_h(MyUtil.createUUID());
			gr1.setName("awayPushHVO");
			gr1.setFieldValue("status", "0");
			gr1.setFieldValue("dirty", "1");
			gr1.setFieldValue("primaryKey", "1");
			gr1.setFieldValue("aPPLIER", this.awayFormBean.getApplier());
			gr1.setFieldValue("iSAPPBILL", "N");
			gr1.setFieldValue("aWAYTYPE", this.awayFormBean.getAwaytype());
			gr1.setFieldValue("aWAYID", String.valueOf(this.awayFormBean.getSummaryId()));
			gr1.setFieldValue("fUN_CODE", "123");
			gr1.setFieldValue("aPPROVEIDEA", "");
			gr1.setFieldValue("dR", "0");
			gr1.setFieldValue("aPPLYDATE", this.awayFormBean.getApplydate());
			gr1.setFieldValue("aPPLYDEPT", this.awayFormBean.getApplydept());
			gr1.setFieldValue("aPPROVEDATE", "");
			gr1.setFieldValue("aPPROVESTATUS", "200");
			gr1.setFieldValue("pK_AWAY_H", this.awayFormBean.getPk_away_h());
			gr1.setFieldValue("iSHRSSBILL", "N");
			gr1.setFieldValue("tS", this.awayFormBean.getTs());
			gr1.setFieldValue("bILLNAME", MyUtil.getLimitLengthString(this.awayFormBean.getBillname(), 50, "…"));
			gr1.setFieldValue("sUBMITTER", "");
			gr1.setFieldValue("pK_CORP", this.awayFormBean.getPk_corp());
			gr1.setFieldValue("cENSOR", "");
			gr1.setFieldValue("pK_BUSITYPE", "");
			gr1.setFieldValue("sUBMIT_DATE", "");
			grs1.add(gr1);
			GroupRecord gr2 = new GroupRecord();
			gr2.setName("awayPushBVO");
			gr2.setFieldValue("status", "0");
			gr2.setFieldValue("dirty", "1");
			gr2.setFieldValue("primaryKey", "1");
			gr2.setFieldValue("wORKFINISH", "");
			gr2.setFieldValue("pSNCODE", this.awayFormBean.getPersonList().get(i).getPsncode());
			gr2.setFieldValue("rEMARK", "");
			gr2.setFieldValue("aHEADFEE", awayFormBean.getAheadfee());
			gr2.setFieldValue("bACKDATE", "");
			gr2.setFieldValue("aWAYENDTIME", OA2HRConstant.getWorkTime(this.awayFormBean.getAwayendtime(),
					this.awayFormBean.getPk_corp(), accountID));
			gr2.setFieldValue("dR", "0");
			gr2.setFieldValue("aWAYBEGINDAY", this.awayFormBean.getAwaybeginday());
			System.err.println(this.awayFormBean.getAwaybeginday());
			gr2.setFieldValue("pLANBEGINTIME", "");
			gr2.setFieldValue("pK_AWAY_H", this.awayFormBean.getPk_away_h());
			gr2.setFieldValue("iFAPPROVE", "N");
			gr2.setFieldValue("pK_AGENTPSN", "");
			gr2.setFieldValue("aWAYADDRESS", this.awayFormBean.getAwayaddress());
			gr2.setFieldValue("tS", this.awayFormBean.getTs());
			gr2.setFieldValue("aWAYBEGINTIME", OA2HRConstant.getWorkTime(this.awayFormBean.getAwaybegintime(),
					this.awayFormBean.getPk_corp(), accountID));
			gr2.setFieldValue("aWAYENDDAY", this.awayFormBean.getAwayendday());
			gr2.setFieldValue("hWORKPROCESS", "");
			gr2.setFieldValue("aWAYOFFSTATUS", "2");
			gr2.setFieldValue("pK_TBM_PSNDOC", this.awayFormBean.getPersonList().get(i).getPk_tbm_psndoc());
			gr2.setFieldValue("aWAYNOTE", MyUtil.getLimitLengthString(this.awayFormBean.getAwaynote(), 500, "…"));
			gr2.setFieldValue("aWAYSUMHOUR", this.awayFormBean.getAwaysumhour());
			System.err.println(this.awayFormBean.getAwaysumhour());
			gr2.setFieldValue("fACTFEE", "");
			gr2.setFieldValue("sUMHOUR", "");
			gr2.setFieldValue("pK_AWAY_B", MyUtil.createUUID());
			gr2.setFieldValue("bACKTIME", "");
			gr2.setFieldValue("pLANBEGINDAY", "");
			gr2.setFieldValue("pLANENDDAY", "");
			gr2.setFieldValue("aWAYPSNORDER", "0");
			gr2.setFieldValue("pLANENDTIME", "");
			grs1.add(gr2);
			reqMo.setReqGroupRecord(grs1);
			IMsgObject respMo = null;
			respMo = Requester.execute(reqMo);
			//System.out.println("!"+respMo);
			log.info(reqMo);
			log.info("~~~~~~~~~~~~~~~~~~~~~~~"+respMo);
			if (!respMo.getResValue("return").equals("false")) {
				//System.out.println("input success");
				log.info(String.valueOf(this.awayFormBean.getSummaryId()) + " input success");
			} else {
				//System.out.println("input fail");
				log.info(String.valueOf(this.awayFormBean.getSummaryId()) + " input fail");
			}
	}}
}
